package ru.nsu.ccfit.dronov;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: Asus
 * Date: 19.12.2009
 * Time: 16:25:46
 * To change this template use File | Settings | File Templates.
 */
public class ProfileController {

    private ProfileBase Base;
    private String BaseFileName;

    //------------------------------------------------------------------------------------------------------------------
    public String getBaseFileName()
    {
        return BaseFileName;
    }
    //------------------------------------------------------------------------------------------------------------------
    public void setBaseFileName(String baseFileName) {
        BaseFileName = baseFileName;
    }
    //------------------------------------------------------------------------------------------------------------------
    public ProfileController() {
        Base=new ProfileBase();
    }
    //------------------------------------------------------------------------------------------------------------------
    public void checkUser(CheckableUser user)
    {
        Base.checkUser(user);
    }
    //------------------------------------------------------------------------------------------------------------------
    public void addUser(Profile user)
    {
        Base.addUser(user);
    }
    //------------------------------------------------------------------------------------------------------------------
    public void saveBase()
    {
        try {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();

            if (Base != null)
            {
                JAXBContext jc;

                jc = JAXBContext.newInstance(Base.getClass());
                Marshaller m = jc.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                m.marshal(Base, buf);

                FileOutputStream writer = new FileOutputStream(BaseFileName);

                writer.write(buf.toByteArray());
            }
        } catch (Exception e) {

            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.       }
        }
    }
    //------------------------------------------------------------------------------------------------------------------
    public void loadBase()
    {
        if (Base != null && BaseFileName !=null)
        {

            try
            {
                File reader = new File("output.xml");
                JAXBContext jc;
                jc = JAXBContext.newInstance(Base.getClass());
                Unmarshaller m = jc.createUnmarshaller();
                Base = (ProfileBase)m.unmarshal(reader);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
